package com.ruoyi.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.user.domain.PassengerUser;
import com.ruoyi.user.mapper.PassengerUserMapper;
import com.ruoyi.user.service.IPassengerUserService;
import com.ruoyi.user.utils.HttpClientUtils;
import com.ruoyi.user.utils.WeChatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-17
 */
@Service
@Slf4j
public class PassengerUserServiceImpl implements IPassengerUserService {
    @Autowired
    private PassengerUserMapper passengerUserMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Resource
    private WeChatUtil weChatUtil;
    @Value("${wxchat.appid}")
    private String appId;
    @Value("${wxchat.AppSecret}")
    private String secret;


    @Override
    public PassengerUser login(String code) {

        //获取微信登录的url
        String url = weChatUtil.getCode2Session(appId,secret,code);
        //发送get请求
        String result = HttpClientUtils.sendGet(url);

        //将返回的json字符串转换为json对象
        JSONObject jsonObject = JSON.parseObject(result);

        //获取openid
        String openid = jsonObject.getString("openid");

        //根据openid查询用户
        PassengerUser user = passengerUserMapper.selectByOpenid(openid);
        //如果用户存在
        if (user != null) {
            //返回用户
            return user;
        }else{
            //创建用户
            user = new PassengerUser();
            user.setOpenid(openid);
            //插入用户
            passengerUserMapper.insert(user);
        }
        //返回用户
        return user;


    }

}
